#include "bubu.h"
#include "onetwo.h"
#include <QDebug>

//布布基本属性的构造函数，在具体的布布界面中还有各自的构造函数
Bubu::Bubu()
{
    movie = head = nullptr;//动画
    hp = atk = state = 0;//血量、攻击力、状态
    speed = 0.0;//速度
}

Bubu::~Bubu()
{
    delete movie;
    delete head;
}

//返回布布的矩形边框
QRectF Bubu::boundingRect() const
{
    return QRectF(-60, -75, 150, 105);
}

//绘制布布
void Bubu::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)
    QImage image = movie->currentImage();
    if (speed < 0.3 && state != 3)
    {
        if (state != 2)
            movie->setSpeed(50);
        int w = image.width();
        int h = image.height();
        for (int i = 0; i < h; ++i)
        {
            uchar *line = image.scanLine(i);
            for (int j = 5; j < w - 5; ++j)
            {
                // 修改红色通道（索引+2），增强红色
                line[(j << 2) + 2] = qMin(255, line[(j << 2) + 2] + 100);
                // 减弱绿色和蓝色通道
                line[(j << 2) + 1] = qMax(0, line[(j << 2) + 1] - 50);
                line[j << 2] = qMax(0, line[j << 2] - 50);
            }
        }
    }
    painter->drawImage(QRectF(-52.5, -75, 105, 105), image);
    if (head)
    {
        image = head->currentImage();
        if (speed < 0.55)
        {
            int w = image.width();
            int h = image.height();
            for (int i = 0; i < h; ++i)
            {
                uchar *line = image.scanLine(i);
                for (int j = 5; j < w - 5; ++j)
                    line[j << 2] = 200;
            }
        }
        painter->drawImage(QRectF(0, -75, 105, 105), image);
    }
}

//布布的检测是否发生碰撞函数
bool Bubu::collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode) const
{
    Q_UNUSED(mode)
    return other->type() == Onetwo::Type && qFuzzyCompare(other->y(), y()) && qAbs(other->x() - x()) < 30;
}

int Bubu::type() const
{
    return Type;
}

void Bubu::setMovie(QString path)
{
    if (movie)
        delete movie;
    movie = new QMovie(path);
    movie->start();
}

void Bubu ::setHead(QString path)
{
    if (head)
        delete head;
    head = new QMovie(path);
    head->start();
}
